import matplotlib.pyplot as plt
import numpy as np
from skimage import data, feature, exposure, io
from skimage.color import rgb2gray
from matplotlib.patches import Rectangle

# 加载示例图像
# image = data.astronaut()
image = io.imread(r'F:\人工智能教材编写\traffic_sign\train\17\017_1_0013.png')
# 将图像转换为灰度图
# gray_image = rgb2gray(image)
# HOG参数设置
orientations = 8
pixels_per_cell = (16, 16)
cells_per_block = (1, 1)
# # 计算HOG特征并可视化，因为是灰度图，不需要 channel_axis 参数
# fd, hog_image = feature.hog(gray_image, orientations=orientations,
#                             pixels_per_cell=pixels_per_cell,
#                             cells_per_block=cells_per_block,
#                             visualize=True
#                             )
# 计算HOG特征并可视化
fd, hog_image = feature.hog(image, orientations=orientations,
                            pixels_per_cell=pixels_per_cell,
                            cells_per_block=cells_per_block,
                            visualize=True,
                            channel_axis=-1
                            )

# 增强对比度
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 10))

# 创建一个3列的图像显示
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(18, 6))

# 显示原始图像
ax1.imshow(image)
ax1.set_title('原始图像')
ax1.axis('off')

# 显示标记了cell的中间图像
ax2.imshow(image)
ax2.set_title('标记了Cell的图像')

# 获取图像尺寸和cell数量
rows, cols = image.shape[:2]
cells_y, cells_x = (rows // pixels_per_cell[0], cols // pixels_per_cell[1])

# 绘制cell网格
for i in range(cells_y):
    for j in range(cells_x):
        # 绘制cell边界
        rect = Rectangle((j * pixels_per_cell[1], i * pixels_per_cell[0]),
                         pixels_per_cell[1], pixels_per_cell[0],
                         linewidth=1, edgecolor='r', facecolor='none')
        ax2.add_patch(rect)

ax2.axis('off')

# 显示重缩放后的HOG图像
ax3.imshow(hog_image_rescaled, cmap=plt.cm.gray)
ax3.set_title('重缩放后的HOG图像')
ax3.axis('off')

plt.tight_layout()
plt.show()